package service

import (
	"IMChat/define"
	"IMChat/models"
	"IMChat/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"time"
)

var upgrader = websocket.Upgrader{}
var wcMap = make(map[string]*websocket.Conn)

func WebSocketMessage(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		utils.FailWithMsg(c, -1, "System Error: "+err.Error())
		return
	}
	defer conn.Close()
	uc := c.MustGet("user_claims").(*utils.UserClaims)
	wcMap[uc.Identity] = conn
	for {
		ms := new(define.MessageStruct)

		err = conn.ReadJSON(ms)

		log.Printf("Message is : %v\n", ms.Message)
		if err != nil {
			log.Printf("Read Error : %v\n", err)
			return
		}
		_, err := models.GetUserRoomByUserIdentityRoomIdentity(uc.Identity, ms.RoomIdentity)
		if err != nil {
			log.Printf("UserIdentity : %v,RoomIdentity : %v Not exists\n", uc.Identity, ms.RoomIdentity)
			return
		}
		mb := new(models.MessageBasic)
		mb.UserIdentity = uc.Identity
		mb.RoomIdentity = ms.RoomIdentity
		mb.Data = ms.Message
		mb.CreatedAt = time.Now().Unix()
		mb.UpdatedAt = time.Now().Unix()
		err = models.InsertOneMessageBasic(mb)
		if err != nil {
			log.Printf("[DB INSERT ERROR]: %v\n", err)
			return
		}

		userRoom, err := models.GetUserRoomByRoomIdentity(ms.RoomIdentity)
		if err != nil {
			log.Printf("[DB ERROR] : %v\n", err)
			return
		}
		for _, room := range userRoom {
			if cc, ok := wcMap[room.UserIdentity]; ok {
				err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))

				if err != nil {
					log.Printf("Write Message Error : %v\n", err)
					return
				}
			}
		}
		//for _, cc := range wcMap {
		//	err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
		//
		//	if err != nil {
		//		log.Printf("Write Message Error : %v\n", err)
		//		return
		//	}
		//}
	}
}
